#include "mutex.hpp"
#include "cond.hpp"
#include "thread.hpp"
#include <queue>
#include <vector>
#include <memory>
#include "log.hpp"

namespace ThreadPoolModule
{
    using namespace LockModule;
    using namespace ThreadModule;
    using namespace CondModule;
    using namespace LogModule;

    using thread_t = std::unique_ptr<Thread>;
    static const int defaultnum = 5;

    template <class T>
    class ThreadPool
    {
    public:
        // 获取单例
        static ThreadPool<T> *GetInstance(int num = defaultnum)
        {
            // 创建单例也需加锁
            if (instance == nullptr)
            {
                LockGuard lg(mutex);
                if (instance == nullptr)
                { // 需要在加锁的情况下再判断一遍
                    instance = new ThreadPool<T>(num);
                    LOG(INFO) << "成功加载单例!";
                    instance->start();
                    LOG(INFO) << "线程池启动！";
                }
            }
            return instance;
        }

        void Enqueue(T &&in) // 右值，支持lamda表达式
        {
            LOG(DEBUG)<<"添加任务";
            LockGuard lg(_mutex);
            if (!_isrunning)
                return;
            _taskq.push(std::move(in));
            LOG(DEBUG)<<"添加任务成功";
            LOG(DEBUG)<<"waitnum: "<<_wait_num;
            if (_wait_num > 0) // 如果队列不为空，唤醒线程处理任务
                _cond.notify();
        }

        void start()
        {
            LockGuard lg(_mutex);
            if (_isrunning)
                return;
            _isrunning = true;
            for (auto &e : _threads)
            {
                e->Start();
                LOG(INFO) << "线程: " << e->Name() << " 启动成功！";
            }
        }
        void wait()
        {
            for (auto &e : _threads)
            {
                e->Join();
                LOG(INFO) << "线程: " << e->Name() << " 回收成功!";
            }
        }
        void stop()
        {
            LockGuard lg(_mutex);
            if (_isrunning)
            {
                _isrunning = false;
                // 让线程处理完任务后自行退出
                if (_wait_num > 0)
                    _cond.notifyall();
            }
        }

    private:
        // 任务队列判空
        bool Isempty() { return _taskq.empty(); }
        // 处理任务
        void HandlerTask(std::string name)
        {
            while (true)
            {
                T t;
                {
                    LockGuard lg(_mutex);
                    // 任务队列为空则等待
                    while (Isempty() && _isrunning)
                    {
                        ++_wait_num;
                        _cond.wait(_mutex);
                        --_wait_num;
                    }
                    // 任务执行完毕并且线程池暂停时，线程退出
                    if (Isempty() && !_isrunning)
                        break;
                    t = _taskq.front();
                    _taskq.pop();
                }
                // 执行任务
                //sleep(1);
                t(name);
            }
            LOG(INFO) << "线程:" << name << "退出";
        }
        ThreadPool(int num) : _num(num), _wait_num(0), _isrunning(false)
        {
            // 创建线程
            for (int i = 0; i < _num; ++i)
            {
                _threads.push_back(std::make_unique<Thread>(std::bind(&ThreadPool::HandlerTask, this, std::placeholders::_1)));
                LOG(INFO) << "创建线程: " << _threads.back()->Name() << " 成功";
            }
        }

        // 成员
        std::vector<thread_t> _threads; // 管理线程
        std::queue<T> _taskq;           // 任务队列
        int _num;                       // 线程总数
        int _wait_num;                  // 等待线程数
        Mutex _mutex;
        Cond _cond;
        bool _isrunning;

        static ThreadPool<T> *instance; // 单例指针
        static Mutex mutex;             // 用于保护单例
    };
    template <class T>
    ThreadPool<T> *ThreadPool<T>::instance = nullptr;
    template <class T>
    Mutex ThreadPool<T>::mutex;
}
